//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"bytes"
	"strings"

	"atomgit.com/openlinksaas/search-proxy/core"
	"github.com/antchfx/htmlquery"
)

type PkgGoParser struct{}

func (parser *PkgGoParser) MatchUrl(url string) bool {
	return strings.HasPrefix(url, "https://pkg.go.dev/search")
}

func (parser *PkgGoParser) Parse(url string) ([]*core.SearchEntry, error) {
	body, err := GetPage(url)
	if err != nil {
		return nil, err
	}

	doc, err := htmlquery.Parse(bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}

	retList := []*core.SearchEntry{}
	pkgElList := htmlquery.Find(doc, "//div[@class='SearchSnippet']")
	for _, pkgEl := range pkgElList {
		summary := ""
		descEl := htmlquery.FindOne(pkgEl, "//p[@class='SearchSnippet-synopsis']")
		if descEl != nil {
			summary = htmlquery.InnerText(descEl)
		}
		linkEl := htmlquery.FindOne(pkgEl, "//h2/a")
		if linkEl != nil {
			retList = append(retList, &core.SearchEntry{
				Title:   strings.ReplaceAll(htmlquery.InnerText(linkEl), " ", ""),
				Url:     "https://pkg.go.dev" + htmlquery.SelectAttr(linkEl, "href"),
				Summary: summary,
			})
		}
	}

	return retList, nil
}
